from django.db import models
from django.contrib.auth import get_user_model
from apps.orders.models import Order

User = get_user_model()


class CommissionRule(models.Model):
    """佣金规则"""
    name = models.CharField(max_length=100, verbose_name='规则名称')
    description = models.TextField(blank=True, verbose_name='规则描述')
    
    # 佣金设置
    commission_rate = models.DecimalField(max_digits=5, decimal_places=4, verbose_name='佣金比例')
    minimum_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='最低金额')
    maximum_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='最高金额')
    
    # 适用范围
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(null=True, blank=True, verbose_name='结束日期')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'commission_rules'
        verbose_name = '佣金规则'
        verbose_name_plural = '佣金规则'
        ordering = ['-created_at']

    def __str__(self):
        return self.name


class CommissionRecord(models.Model):
    """佣金记录"""
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='commission_records')
    rule = models.ForeignKey(CommissionRule, on_delete=models.CASCADE, related_name='commission_records')
    
    order_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单金额')
    commission_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='佣金金额')
    commission_rate = models.DecimalField(max_digits=5, decimal_places=4, verbose_name='实际佣金比例')
    
    # 结算状态
    STATUS_CHOICES = [
        ('pending', '待结算'),
        ('calculated', '已计算'),
        ('paid', '已支付'),
        ('cancelled', '已取消'),
    ]
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='结算状态')
    
    calculated_at = models.DateTimeField(null=True, blank=True, verbose_name='计算时间')
    paid_at = models.DateTimeField(null=True, blank=True, verbose_name='支付时间')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'commission_records'
        verbose_name = '佣金记录'
        verbose_name_plural = '佣金记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order.order_number} - {self.commission_amount}"


class Invoice(models.Model):
    """发票管理"""
    INVOICE_TYPE_CHOICES = [
        ('personal', '个人'),
        ('company', '公司'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待开具'),
        ('issued', '已开具'),
        ('cancelled', '已作废'),
    ]

    order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='invoice')
    invoice_type = models.CharField(max_length=20, choices=INVOICE_TYPE_CHOICES, verbose_name='发票类型')
    
    # 发票信息
    invoice_title = models.CharField(max_length=200, verbose_name='发票抬头')
    invoice_content = models.CharField(max_length=100, default='图书', verbose_name='发票内容')
    tax_number = models.CharField(max_length=50, blank=True, verbose_name='税号')
    
    # 金额信息
    invoice_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='发票金额')
    tax_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='税额')
    
    # 发票详情
    invoice_number = models.CharField(max_length=50, blank=True, verbose_name='发票号码')
    invoice_code = models.CharField(max_length=50, blank=True, verbose_name='发票代码')
    invoice_date = models.DateField(null=True, blank=True, verbose_name='开票日期')
    invoice_url = models.URLField(blank=True, verbose_name='发票下载链接')
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='发票状态')
    
    # 备注
    note = models.TextField(blank=True, verbose_name='备注')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'invoices'
        verbose_name = '发票'
        verbose_name_plural = '发票'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order.order_number} - {self.invoice_title}"


class FinancialReport(models.Model):
    """财务报表"""
    REPORT_TYPE_CHOICES = [
        ('daily', '日报'),
        ('weekly', '周报'),
        ('monthly', '月报'),
        ('yearly', '年报'),
    ]

    report_type = models.CharField(max_length=20, choices=REPORT_TYPE_CHOICES, verbose_name='报表类型')
    start_date = models.DateField(verbose_name='开始日期')
    end_date = models.DateField(verbose_name='结束日期')
    
    # 收入统计
    total_revenue = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='总收入')
    book_sales = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='图书销售')
    shipping_fee = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='运费收入')
    
    # 支出统计
    total_expenses = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='总支出')
    purchase_cost = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='采购成本')
    commission_cost = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='佣金支出')
    operating_expenses = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='运营费用')
    
    # 利润
    net_profit = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='净利润')
    
    # 订单统计
    total_orders = models.IntegerField(default=0, verbose_name='订单总数')
    completed_orders = models.IntegerField(default=0, verbose_name='已完成订单')
    cancelled_orders = models.IntegerField(default=0, verbose_name='已取消订单')
    refund_orders = models.IntegerField(default=0, verbose_name='退款订单')
    
    # 文件信息
    report_file = models.FileField(upload_to='financial_reports/', blank=True, verbose_name='报表文件')
    generated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='generated_reports')
    generated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'financial_reports'
        verbose_name = '财务报表'
        verbose_name_plural = '财务报表'
        unique_together = ['report_type', 'start_date', 'end_date']
        ordering = ['-start_date']

    def __str__(self):
        return f"{self.get_report_type_display()} - {self.start_date} 至 {self.end_date}"


class PaymentTransaction(models.Model):
    """支付交易记录"""
    TRANSACTION_TYPE_CHOICES = [
        ('order_payment', '订单支付'),
        ('refund', '退款'),
        ('commission', '佣金支付'),
        ('other', '其他'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待处理'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('failed', '失败'),
        ('cancelled', '已取消'),
    ]

    transaction_id = models.CharField(max_length=100, unique=True, verbose_name='交易ID')
    order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True, blank=True, related_name='transactions')
    
    transaction_type = models.CharField(max_length=20, choices=TRANSACTION_TYPE_CHOICES, verbose_name='交易类型')
    amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='交易金额')
    
    # 支付信息
    payment_method = models.CharField(max_length=50, verbose_name='支付方式')
    payment_channel = models.CharField(max_length=50, blank=True, verbose_name='支付渠道')
    
    # 状态信息
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='交易状态')
    error_message = models.TextField(blank=True, verbose_name='错误信息')
    
    # 时间信息
    initiated_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')
    
    # 第三方信息
    third_party_id = models.CharField(max_length=100, blank=True, verbose_name='第三方交易ID')
    third_party_response = models.JSONField(default=dict, blank=True, verbose_name='第三方响应')

    class Meta:
        db_table = 'payment_transactions'
        verbose_name = '支付交易'
        verbose_name_plural = '支付交易'
        ordering = ['-initiated_at']

    def __str__(self):
        return f"{self.transaction_id} - {self.amount}"
